package com.fs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.mapper.SysAdminMenusMapper;
import com.fs.pojo.SysAdminMenus;
import com.fs.service.SysAdminMenuService;
import com.fs.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysAdminMenuServiceImpl implements SysAdminMenuService {

    @Autowired
    private SysAdminMenusMapper sysAdminMenusMapper;

    @Override
    public SysResult getAll() {
        return SysResult.success(sysAdminMenusMapper.selectList(null));
    }

    @Override
    public SysResult menuSelect() {
        QueryWrapper<SysAdminMenus> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("level",3);
        List<SysAdminMenus> list = sysAdminMenusMapper.selectList(queryWrapper);
        SysAdminMenus firstMenu = new SysAdminMenus().setName("一级菜单")
                .setId(0)
                .setParentId(-1);
        list.add(firstMenu);
        return SysResult.success(list);
    }

    @Override
    public SysAdminMenus getById(Integer parentId) {
        return sysAdminMenusMapper.selectById(parentId);
    }

    @Transactional
    @Override
    public void save(SysAdminMenus menu) {
        if(menu.getLevel()==1 || menu.getLevel()==2)menu.setPermission(null);
        Date now = new Date();
        menu.setCreated(now)
                .setUpdated(now);
        sysAdminMenusMapper.insert(menu);
    }

    @Transactional
    @Override
    public void updateById(SysAdminMenus menu) {
        sysAdminMenusMapper.updateById(menu);
    }

    @Override
    public List<SysAdminMenus> queryListParentId(Long parentId, List<Long> menuIdList) {
        List<SysAdminMenus> menuList = queryListParentId(parentId);
        if(menuIdList == null){
            return menuList;
        }

        List<SysAdminMenus> userMenuList = new ArrayList<>();
        for(SysAdminMenus menu : menuList){
            if(menuIdList.contains(menu.getId())){
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    @Override
    public List<SysAdminMenus> queryListParentId(Long parentId) {
        return sysAdminMenusMapper.queryListParentId(parentId);
    }

    @Transactional
    @Override
    public void delete(long menuId) {
        sysAdminMenusMapper.deleteById(menuId);
    }
}
